<template>
    <div>
        <Modal v-model="isShowModal" :title="title" @on-cancel="hide()" :mask-closable="false" fullscreen>

            <div class="j-sku-row" v-for="(item,index) in skuItemList" :key="index">
                <Card>
                    <div class="j-sku-input">
                        <Input v-model="item.skuName" placeholder="规格名称"
                               style="width: 150px; margin-right: 10px"></Input>
                        <Input v-model="item.skuValue" placeholder="规格值"
                               style="width: 150px; margin-right: 10px"></Input>
                        <Button type="primary" style="margin-right: 10px" @click="addCheckBoxList(item)">增加规格值</Button>
                        <Button type="error" :disabled="skuItemList.length <= 1" @click="delLine(index)">删除这一行</Button>
                    </div>
                    <div class="j-sku-select" v-if="item.checkBoxList.length">
                        <CheckboxGroup v-model="item.checkList" @on-change="skuCheckChange($event, index)">
                            <Checkbox :label="v.skuName + '^|^' + v.skuVal" border v-for="(v,i) in item.checkBoxList"
                                      :key="i">
                                {{v.skuVal}}
                            </Checkbox>
                        </CheckboxGroup>
                    </div>
                </Card>
            </div>
            <Button style="margin-top: 10px; margin-bottom: 10px" type="primary" @click="addSkuLine">新增一行规格</Button>
            <Card>
                <Table border :columns="columns" :data="data" size="small">

                    <template slot-scope="{ row, index }" slot="skuPurchasePrice">
                        <Input v-model.trim="data[index].skuPurchasePrice" min="0" style="width:100px"></Input>
                    </template>

                    <template slot-scope="{ row, index }" slot="skuPrice">
                        <Input v-model.trim="data[index].skuPrice" min="0" style="width:100px"></Input>
                    </template>

                    <template slot-scope="{ row, index }" slot="skuIntegral">
                        <Input v-model.trim="data[index].skuIntegral" min="0" style="width:100px"></Input>
                    </template>

                    <template slot-scope="{ row, index }" slot="specImages">
                        <div class="hs-upload-image-box">
                            <Upload :action="action" :headers="headers" :show-upload-list="false" name="file"
                                    :on-success="(response, file, fileList)=>{uploadSuccess(response, file, fileList, index)}">
                                <div class="hs-upload-add" v-if="!row.specImages">
                                    <Icon type="md-add" size="30"/>
                                </div>
                                <div class="hs-upload-image" v-if="row.specImages">
                                    <img :src="data[index].specImages">
                                </div>
                            </Upload>
                        </div>
                    </template>

                </Table>
            </Card>

            <!-- 重写对话框底部按钮 -->
            <div slot="footer">
                <Button @click="hide()">取消</Button>
                <Button type="primary" @click="handleSubmit()" :loading="loadingBtn">
                    <span v-if="!loadingBtn">确定</span>
                    <span v-else>请稍候...</span>
                </Button>
            </div>
        </Modal>
    </div>
</template>

<script>
    export default {
        name: "goods-sku-ope",
        props: ['goodsSkuList', 'specGroup'],
        data() {
            return {
                isShowModal: false,
                loadingBtn: false,
                title: '设置商品规格',
                action: this.$uploadURL,
                headers: {
                    token: JSON.parse(sessionStorage.getItem('J-TOKEN')).token
                },
                skuItemList: [
                    {
                        skuName: '',
                        skuValue: '',
                        checkBoxList: [],
                        checkList: []
                    }
                ],
                skuNameList: [],
                columns: [
                    {
                        title: '市场价（元）',
                        minWidth: 120,
                        slot: 'skuPurchasePrice'
                    },
                    {
                        title: '售价（元）',
                        minWidth: 120,
                        slot: 'skuPrice'
                    },
                    {
                        title: '赠送知豆（个）',
                        minWidth: 120,
                        slot: 'skuIntegral'
                    },
                    {
                        title: '图片',
                        minWidth: 140,
                        slot: 'specImages'
                    }
                ],
                data: []
            }
        },
        methods: {
            // 新增一行规格
            addSkuLine() {
                this.skuItemList.push({
                    skuName: '',
                    skuValue: '',
                    checkBoxList: [],
                    checkList: []
                });
            },
            // 删除一行规格
            delLine(index) {
                this.skuItemList.splice(index, 1);
                // 选中的规格值如果为空了，删除表头对应的规格名称
                this.columns.splice(index, 1);
                this.arrangeTableData();
            },
            // 新增规格值
            addCheckBoxList(item) {
                let flag = true;
                if (item.skuValue && item.skuName) {
                    item.checkBoxList.forEach(v => {
                        if (v.skuVal === item.skuValue) {
                            this.$Message.error("该规格值已存在");
                            flag = false;
                        }
                    });
                    if (flag) {
                        item.checkBoxList.push({
                            skuVal: item.skuValue,
                            skuName: item.skuName
                        });
                    }
                    item.skuValue = "";
                } else {
                    this.$Message.error("规格名和规格值不能为空");
                }
            },
            // 勾选规格值时
            skuCheckChange(e, index) {

                // 判断规格名称是否填写
                if (!this.skuItemList[index].skuName) {
                    this.skuItemList[index].checkList = [];
                    this.$Message.error("规格名称不能为空");
                    return false;
                }

                // 整理表格数据
                this.arrangeTableData();

                // 判断每一行下面选中的规格值是否为空
                if (!this.skuItemList[index].checkList.length) {
                    // 判断规格名称数组是否为空，防止删除表头的其他静态数据
                    if (!this.skuNameList.length) {
                        index = 0;
                    }
                    // 选中的规格值如果为空了，删除表头对应的规格名称
                    this.columns.splice(index, 1);
                }
            },
            // 整理表格数据
            arrangeTableData() {

                let skuNameList = [];
                let skuValList = [];

                // 整理规格值和规格名称放到数组里面
                this.skuItemList.forEach(v => {
                    if (v.checkList.length > 0) {
                        skuValList.push(v.checkList);
                        skuNameList.push(v.skuName);
                    }
                });

                // 规格名称赋值
                this.skuNameList = skuNameList;

                // 整理规格值，整合数组
                function getProducts(specs) {
                    if (!specs || specs.length == 0) {
                        return [];
                    } else {
                        return joinSpec([[]], specs, 0, specs.length - 1);
                    }

                    function joinSpec(prevProducts, specs, i, max) {
                        var currentProducts = [],
                            currentProduct,
                            currentSpecs = specs[i];
                        if (i > max) {
                            return prevProducts;
                        }
                        prevProducts.forEach(function (prevProduct) {
                            currentSpecs.forEach(function (spec) {
                                currentProduct = prevProduct.slice(0);
                                currentProduct.push(spec);
                                currentProducts.push(currentProduct);
                            });
                        });
                        return joinSpec(currentProducts, specs, ++i, max);
                    }
                }

                let arr = getProducts(skuValList);

                // 将规格名称加入表头
                for (let i in skuNameList) {
                    let flag = true;
                    this.columns.forEach(x => {
                        if (x.key == skuNameList[i]) {
                            flag = false;
                        }
                    });
                    if (flag) {
                        // console.log(skuNameList[i]);
                        this.columns.splice(i, 0, {
                            title: skuNameList[i],
                            minWidth: 120,
                            key: skuNameList[i]
                        });
                    }
                }

                // 将数据加入表格data
                let tableData = [];
                arr.forEach(v => {
                    let obj = {};
                    v.forEach(val => {
                        obj[val.split("^|^")[0]] = val.split("^|^")[1];
                    });
                    obj.skuPurchasePrice = 0;
                    obj.skuPrice = 0;
                    obj.skuIntegral = 0;
                    obj.specImages = '';
                    tableData.push(obj);
                });
                this.$nextTick(() => {
                    this.data = tableData;
                })

            },
            // 上传图片成功
            uploadSuccess(response, file, fileList, index) {
                if (response.status == 200) {
                    // console.log(response.data)
                    this.data[index].specImages = response.data;
                }
                if (response.status == 201) {
                    this.$Message.error(response.msg);
                }
                if (response.status == 500) {
                    this.$Notice.error({
                        title: '服务器内部错误',
                        desc: '上传图片接口报错',
                        duration: 0
                    });
                }
            },
            // 点击提交验证
            handleSubmit() {
                //规格数组
                let arr = [];
                //规格值数组
                let specGrouArr = [];
                let flag = false;

                this.data.forEach(v => {
                    if (!v.skuPurchasePrice) {
                        flag = true;
                        this.$Message.error("规格市场价没有填写");
                    }
                    if (!v.skuPrice) {
                        flag = true;
                        this.$Message.error("规格售价没有填写");
                    }
                    if (!v.skuIntegral) {
                        flag = true;
                        this.$Message.error("规格赠送知豆没有填写");
                    }
                    let obj = {
                        skuPurchasePrice: v.skuPurchasePrice,
                        skuPrice: v.skuPrice,
                        skuIntegral: v.skuIntegral,
                        specImages: v.specImages
                    };
                    let specName = [];
                    let specValue = [];
                    let specGrou = {};
                    this.skuNameList.forEach(val => {
                        specName.push(val);
                        specValue.push(v[val]);
                        specGrou[val] = v[val];
                    });
                    obj.specName = specName.join(",");
                    obj.specValue = specValue.join(",");
                    arr.push(obj);
                    specGrouArr.push(specGrou);
                });
                if (flag) {
                    return;
                } else {
                    this.$emit("skuEditDone", {
                        goodsSkuList: arr,
                        specGroup: specGrouArr
                    });
                    this.hide();
                }
            },
            // 显示模态框
            show() {
                this.isShowModal = true;
                // console.log(this.goodsSkuList);
                // console.log(this.specGroup);

                if(this.goodsSkuList.length){
                    this.skuNameList = this.goodsSkuList[0].specName.split(",");
                    this.skuItemList = [];
                    this.skuNameList.forEach((v, k) => {
                        let obj = {
                            skuName: v,
                            skuValue: "",
                            checkBoxList: [],
                            checkList: []
                        };
                        this.goodsSkuList.forEach(val => {
                            let obj1 = val.specValue.split(",");
                            let flag = true;
                            obj.checkBoxList.forEach(value => {
                                if (obj1[k] == value.skuVal) {
                                    flag = false;
                                    return;
                                }
                            });
                            if (flag) {
                                obj.checkBoxList.push({
                                    skuVal: obj1[k],
                                    skuName: v
                                });
                                obj.checkList.push(v + "^|^" + obj1[k]);
                            }
                        });
                        this.skuItemList.push(obj);
                    });

                    // 将规格名称加入表头
                    for (let i in this.skuNameList) {
                        let flag = true;
                        this.columns.forEach(x => {
                            if (x.key == this.skuNameList[i]) {
                                flag = false;
                            }
                        });
                        if (flag) {
                            // console.log(this.skuNameList[i]);
                            this.columns.splice(i, 0, {
                                title: this.skuNameList[i],
                                minWidth: 120,
                                key: this.skuNameList[i]
                            });
                        }
                    }

                    this.goodsSkuList.forEach(v => {
                        let obj = {
                            skuPurchasePrice: v.purchasePrice || v.skuPurchasePrice,
                            skuPrice: v.price || v.skuPrice,
                            skuIntegral: v.integral || v.skuIntegral,
                            specImages: v.specImages
                        };
                        let specNameArr = v.specName.split(",");
                        let specValArr = v.specValue.split(",");
                        specNameArr.forEach((val, key) => {
                            obj[val] = specValArr[key];
                        });
                        this.data.push(obj);
                    });

                }

                /*this.skuItemList.push({
                    skuName: '',
                    skuValue: '',
                    checkBoxList: [],
                    checkList: []
                });*/
            },
            // 关闭模态框
            hide() {
                this.isShowModal = false;
                this.skuItemList = [
                    {
                        skuName: '',
                        skuValue: '',
                        checkBoxList: [],
                        checkList: []
                    }
                ];
                this.skuNameList = [];
                this.columns = [
                    {
                        title: '市场价（元）',
                        minWidth: 120,
                        slot: 'skuPurchasePrice'
                    },
                    {
                        title: '售价（元）',
                        minWidth: 120,
                        slot: 'skuPrice'
                    },
                    {
                        title: '赠送知豆（个）',
                        minWidth: 120,
                        slot: 'skuIntegral'
                    },
                    {
                        title: '图片',
                        minWidth: 140,
                        slot: 'specImages'
                    }
                ];
                this.data = [];

            }
        }
    }
</script>

<style scoped lang="less">
    .j-sku-row {
        margin-top: 10px;
        transition: all .3s;
        -webkit-transition: all .3s;
    }

    .j-sku-row:first-of-type {
        margin-top: 0px;
    }

    .j-sku-select {
        margin-top: 10px;
        padding: 10px;
        background-color: #f8f8f9;
    }


    .hs-upload-image-box {
        display: flex;
        align-items: center;
        position: relative;
        padding: 5px;

        .hs-upload-image {
            width: 100px;
            height: 100px;
            /*margin-top: -8px;*/
            margin-left: 10px;
            border: 1px solid #efefef;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;

            .hs-upload-image-delete {
                position: absolute;
                top: -8px;
                right: -8px;
                width: 20px;
                height: 20px;
                background-color: red;
                display: flex;
                align-items: center;
                justify-content: center;
                color: #ffffff;
                border-radius: 50%;
            }

            .hs-upload-image-setting {
                position: absolute;
                bottom: 0;
                width: 100%;
                color: #ffffff;
                height: 40px;
                display: none;
                align-items: center;
                justify-content: center;
                background-color: rgba(0, 0, 0, .8);
            }

            img {
                width: 100%;
                height: 100%;
            }
        }

        .hs-upload-add {
            cursor: pointer;
            width: 100px;
            height: 100px;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 1px dashed #cccccc;
            transition: all .3s;

            &:hover {
                color: #2d8cf0;
                border: 1px dashed #2d8cf0;
            }
        }
    }
</style>